import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'flutter_plugin_platform_interface.dart';

typedef TypeOnRecvData = void Function(int value);

class FlutterPlugin {
  static const eventChannel =
      EventChannel('com.ducafecat.counter/eventChannel');
  StreamSubscription? _streamSubscription;
  TypeOnRecvData? _onRecvData;

  Future<String?> getPlatformVersion() {
    return FlutterPluginPlatform.instance.getPlatformVersion();
  }

  Future<int?> add(int a, int b) {
    return FlutterPluginPlatform.instance.add(a, b);
  }

  Future<void> startCounting(TypeOnRecvData onRecvData) async {
    _onRecvData = onRecvData;
    if (_streamSubscription == null) {
      bool? isStarting = await FlutterPluginPlatform.instance.startCounting();
      if (isStarting == true) {
        _streamSubscription =
            eventChannel.receiveBroadcastStream().listen(_listenStream);
      }
    }
  }

  void cancelCounting() {
    _streamSubscription?.cancel();
    _streamSubscription = null;
    _onRecvData = null;
  }

  void _listenStream(value) {
    debugPrint("Recived From Native: $value\n");
    _onRecvData?.call(value);
    if (value == 50) {
      cancelCounting();
    }
  }
  void dispose() {
    cancelCounting();
  }

}
